<template>
  <div>
    <MyTable :data="goodsList">
      <template #header>
        <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>

      <template #body="scope">
        <td>{{ scope.index + 1 }}</td>
        <td>{{ scope.row.goods_name }}</td>
        <td>¥ {{ scope.row.goods_price }}</td>
        <td>
          <input
            v-if="scope.row.inputVisible"
            class="tag-input form-control"
            type="text"
            v-focus
            @blur="scope.row.inputVisible = false"
            @keyup.enter="handleEnter(scope.row, $event)"
            @keyup.esc="$event.target.value = ''"
          />
          <button
            v-else
            class="btn btn-primary btn-sm add-tag"
            @click="scope.row.inputVisible = true"
          >
            +Tag
          </button>
          <span
            v-for="tag in scope.row.tags"
            :key="tag"
            class="badge badge-warning"
            >{{ tag }}</span
          >
        </td>
        <td>
          <button class="btn btn-danger btn-sm" @click="delFn(scope.index)">
            删除
          </button>
        </td>
      </template>
    </MyTable>
  </div>
</template>

<script>
import MyTable from "./MyTable";
export default {
  data() {
    return {
      goodsList: [],
    };
  },
  components: {
    MyTable,
  },
  methods: {
    // 初始化商品的数据
    async getGoodsList() {
      // 发送ajax请求
      const res = await this.$axios.get("/api/goods");
      const { status, data } = res.data;
      if (status !== 0) return console.log("获取商品列表失败");
      // 请求成功
      this.goodsList = data;
    },
    delFn(index) { // 删除
      this.goodsList.splice(index, 1);
    },
    handleEnter(row, e) { // 回车-新增
      if (e.target.value.trim() === "") return;
      row.tags.push(e.target.value);
      e.target.value = "";
      row.inputVisible = false; // 关闭
    },
  },
  created() {
    this.getGoodsList();
  },
};
</script>

<style scoped lang="less">
.my-goods-list {
  .badge {
    margin-right: 5px;
  }
}
</style>